<template>
  <div class="app-container">
    <el-form :model="queryParams" v-show="showSearch" ref="queryForm" :inline="true">
      <el-form-item label="流程实例ID" prop="processInstanceId">
        <el-input
          v-model="queryParams.processInstanceId" placeholder="流程实例ID精确查询" clearable size="default" style="width: 240px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="流程编码" prop="wfCodeLike">
        <el-input
          v-model="queryParams.wfCodeLike" placeholder="流程编码模糊查询" clearable size="default" style="width: 240px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="业务KEY" prop="businessKeyLike">
        <el-input
          v-model="queryParams.businessKeyLike" placeholder="业务Key模糊查询" clearable size="default" style="width: 240px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="流程主题" prop="businessSubjectLike">
        <el-input v-model="queryParams.businessSubjectLike" placeholder="流程主题模糊查询" clearable size="default" style="width: 240px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="发起时间">
        <el-date-picker
          v-model="dateRange" size="default" style="width: 240px" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
          start-placeholder="开始日期" end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item>
        <search-button @click="handleQuery" />
        <reset-button @click="resetQuery" />
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <right-toolbar @query-table="getList" v-model:showSearch="showSearch" />
    </el-row>
    <el-tabs v-model="tabs" @tab-click="handleClick">
      <el-tab-pane label="流转中" name="progress">
        <el-table v-loading="progressLoading" :data="progressList">
          <el-table-column label="流程实例ID" prop="processInstanceId" width="240" align="center" />
          <el-table-column label="业务KEY" prop="businessKey" width="150" align="center" :show-overflow-tooltip="true" />
          <el-table-column label="流程主题" prop="businessSubject" min-width="250" align="center" :show-overflow-tooltip="true" />
          <el-table-column label="流程名称" prop="deploymentName" min-width="200" align="center" :show-overflow-tooltip="true">
            <template #default="scope">
              <span>{{ scope.row.deploymentName+"("+scope.row.processDefinitionId+")" }}</span>
            </template>
          </el-table-column>
          <el-table-column label="发起时间" prop="processCreateTime" width="160" align="center">
            <template #default="scope">
              <span>{{ parseTime(scope.row.processCreateTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300px" fixed="right">
            <template #default="scope">
              <text-detail-button text="审批记录" @click="showAppHistoryModal(scope.row)" />
              <text-detail-button text="流转过程" @click="showFlowImgModal(scope.row, false)" />
              <text-delete-button text="作废" :subject="scope.row.businessSubject" @click="discardMyProcess(scope.row)" />
              <text-edit-button text="撤回" @click="handleRevoke(scope.row)" />
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="progressTotal>0" :total="progressTotal" v-model:page="progressQueryParams.pageNum" v-model:limit="progressQueryParams.pageSize"
          @pagination="pageGetProgressList" />
        <div class="empty"></div>
      </el-tab-pane>
      <el-tab-pane label="已完成" name="finish">
        <el-table v-loading="finishLoading" :data="finishList">
          <el-table-column label="流程实例ID" prop="processInstanceId" width="240" align="center" />
          <el-table-column label="业务KEY" prop="businessKey" width="150" align="center" :show-overflow-tooltip="true" />
          <el-table-column label="流程主题" prop="businessSubject" min-width="250" align="center" :show-overflow-tooltip="true" />
          <el-table-column label="流程名称" prop="deploymentName" min-width="200" align="center" :show-overflow-tooltip="true">
            <template #default="scope">
              <span>{{ scope.row.deploymentName+"("+scope.row.processDefinitionId+")" }}</span>
            </template>
          </el-table-column>
          <el-table-column label="发起时间" prop="processCreateTime" width="160" align="center">
            <template #default="scope">
              <span>{{ parseTime(scope.row.processCreateTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="结束时间" prop="processEndTime" width="160" align="center">
            <template #default="scope">
              <span>{{ parseTime(scope.row.processEndTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180px" fixed="right">
            <template #default="scope">
              <text-detail-button text="审批记录" @click="showAppHistoryModal(scope.row)" />
              <text-detail-button text="流转过程" @click="showFlowImgModal(scope.row, true)" />
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="finishTotal>0" :total="finishTotal" v-model:page="finishQueryParams.pageNum" v-model:limit="finishQueryParams.pageSize"
          @pagination="pageGetFinishList" />
        <div class="empty"></div>
      </el-tab-pane>
    </el-tabs>
    <!-- 查询审批记录 -->
    <drag-dialog :title="title" :close-on-click-modal="false" v-model="showHistoryOpen" width="85%" append-to-body>
      <wf-approve-history :processInstanceId="processInstanceId" :wfStatusOptions="wfStatusOptions" :doneViewObject="doneViewObject" />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">关 闭</el-button>
        </div>
      </template>
    </drag-dialog>

    <!-- 查看审批过程 -->
    <drag-dialog :title="title" :close-on-click-modal="false" v-model="showFlowOpen" width="85%" append-to-body>
      <bpmn-viewer v-if="isFlowable && showFlowOpen" :wfCode="wfCode" :processInstanceId="processInstanceId" />
      <wf-run-image v-else :processInstanceId="processInstanceId" :formModelVersionId="formModelVersionId" :showCurrentApproverList="showCurrentApproverList" />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">关闭</el-button>
        </div>
      </template>
    </drag-dialog>
  </div>
</template>
<script>
import { getProgressList, getFinishList, discardMyProcess } from "@wf/api/wf/task/start";
import WfRunImage from "@/components/Zmids/Workflow/WfRunImage.vue";
import WfApproveHistory from "@/components/Zmids/Workflow/WfApproveHistory.vue"
import BpmnViewer from '@wf/components/bpmnjs/bpmnViewer'
import {isEnableRevoke,revokeByProcessInstanceId} from "@/platform/wf/api/wf/task/start.js";

export default {
  name: 'WfTaskStart',
  components: { BpmnViewer, WfApproveHistory, WfRunImage },
  data() {
    return {
      //遮罩层
      progressLoading: true,
      // 选择的流程实例ID
      processInstanceId: "",
      // 是否显示当前审批人列表
      showCurrentApproverList: false,
      finishLoading: true,
      loading: false,
      //tabs默认选中第一个
      tabs: "progress",
      //流程状态
      wfStatusOptions: [],
      // 显示搜索条件
      showSearch: true,
      // 日期范围
      dateRange: [],
      //列表数据
      progressList: [],
      finishList: [],
      showHistoryList: [],
      showFlowList: [],
      //总条数
      progressTotal: 0,
      finishTotal: 0,
      // 查询参数
      queryParams: {
        processInstanceId: undefined,
        wfCodeLike: undefined,
        businessKeyLike: undefined,
        businessSubjectLike: undefined,
      },
      progressQueryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      finishQueryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      showHistoryOpen: false,
      showFlowOpen: false,
      title: "",
      //图片流
      imageContent: '',
      //已办流程row
      doneViewObject: {},
      formModelVersionId: '', //低代码表单版本ID
      wfCode: ''
    };
  },
  computed: {
    isFlowable(){
      return import.meta.env.VITE_FLOW_TYPE == 'flowable'
    }
  },
  created() {
    this.getList();
    this.getDicts("wf_approve_status").then(response => {
      this.wfStatusOptions = response.data;
    });
  },
  methods: {
    // 搜索按钮操作
    handleQuery() {
      // 组合查询参数
      var params = this.addDateRange(this.queryParams, ["processCreateTimeStart", "processCreateTimeEnd"], this.dateRange);
      this.progressQueryParams = {pageNum: 1,pageSize: this.progressQueryParams.pageSize,...params};
      this.finishQueryParams = {pageNum: 1,pageSize: this.finishQueryParams.pageSize,...params};

      this.getList();
    },
    // 重置按钮操作
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    //获取数据
    getList() {
      this.pageGetProgressList();
      this.pageGetFinishList();
    },

    //查看流程中列表
    pageGetProgressList() {
      this.progressLoading = true;
      getProgressList(this.progressQueryParams).then(
        response => {
          this.progressList = response.data.list;
          this.progressTotal = response.data.total;
          this.progressLoading = false;
        });
    },

    //查询流程结束列表
    pageGetFinishList() {
      this.finishLoading = true;
      getFinishList(this.finishQueryParams).then(
        response => {
          this.finishList = response.data.list;
          this.finishTotal = response.data.total;
          this.finishLoading = false;
        });
    },
    //tabs监听事件
    handleClick(tab, event) {
    },
    // 查询审批记录
    showAppHistoryModal(row) {
      this.title = '审批记录';
      this.processInstanceId = row.processInstanceId;

      this.doneViewObject = row;
      this.doneViewObject.doneViewUrl = row.startViewUrl;
      this.doneViewObject.doneViewFrameUrl = row.startViewFrameUrl;

      this.showHistoryOpen = true;
    },
    // 查看流转过程
    showFlowImgModal(row,isFinished) {
      this.title = "查看流转过程";
      this.showFlowOpen = true;
      this.processInstanceId = row.processInstanceId;
      this.wfCode = row.wfCode;
      const { params } = row
      if(params.variables){
        const varObj = JSON.parse(params.variables)
        this.formModelVersionId = varObj.formModelVersionId ? varObj.formModelVersionId : undefined
      }
      this.showCurrentApproverList = !isFinished;
    },
    reset() {
      this.showHistoryList = [];
      this.showFlowList = [];
      // 选择的流程实例ID
      this.processInstanceId = "";
      this.formModelVersionId = ""
      // 是否显示当前审批人列表
      this.showCurrentApproverList = false;
      // 重置已办流程row
      this.doneViewObject = {};
    },
    // 统一取消按钮
    cancel() {
      this.applyCommonOpen = false;
      this.showHistoryOpen = false;
      this.showFlowOpen = false;
      this.reset();
    },
    // 作废我发起的工作流
    discardMyProcess(row) {
      this.$prompt('请输入作废理由', '提示', {
        confirmButtonText: '作废',
        cancelButtonText: '取消',
        inputPattern: /.+/,
        inputErrorMessage: '作废理由不可以为空'
      }).then(({ value }) => {
        return discardMyProcess({ "processInstanceId": row.processInstanceId, "reason": value });
      }).then(() => {
        this.msgSuccess("流程已作废");
        this.getList();
      });
    },
    // 处理撤回
    handleRevoke(row) {
      isEnableRevoke({ "processInstanceId": row.processInstanceId}).then(response => {
        if(response.data){
          this.$prompt('请输入撤回理由', '提示', {
            confirmButtonText: '撤回',
            cancelButtonText: '取消',
            inputPattern: /.+/,
            inputErrorMessage: '撤回理由不可以为空'
          }).then(({ value }) => {
            return revokeByProcessInstanceId({ "processInstanceId": row.processInstanceId, "reason": value });
          }).then(() => {
            this.msgSuccess("流程已撤回");
            this.getList();
          });
        }else{
          this.$message({
            message: '当前流程第一个节点的发起人不是当前用户，无法撤回，请联系管理员',
            type: 'warning'
          });
        }
      });
    }
  }
}
</script>
<style lang="scss" scoped>
.empty {
  min-height: 10px;
}
</style>
